package com.atom.app.mvvm.net.interceptor

import android.content.Intent
import com.atom.app.mvvm.AppModel
import com.atom.app.mvvm.net.bean.TokenResult
import com.atom.app.mvvm.stack.AppStackManager
import com.atom.app.mvvm.ui.activities.LoginActivity
import com.atom.module.logger.Logger
import kotlinx.coroutines.runBlocking
import okhttp3.Authenticator
import okhttp3.Request
import okhttp3.Response
import okhttp3.Route

class TokenAuthenticator : Authenticator {

    override fun authenticate(route: Route?, response: Response): Request? {
        // 避免无限循环：如果这个请求已经是刷新 token 的请求，不再重试
        if (response.request.url.encodedPath.contains("/system/refresh")) {
            return null // 刷新失败，不再重试
        }
        val refreshToken = AppModel.tokenRefreshGet()
        if (refreshToken.isNullOrBlank()) {
            // 无 refreshToken，跳转登录（需在主线程）
            redirectToLogin()
            return null
        }
        // 同步调用刷新接口（Authenticator 是在后台线程运行的）
        return try {
            val newTokens = runBlocking {
                AppModel.netApi.refreshToken(
                    TokenResult().apply {
                        this.accessToken = AppModel.tokenAccessGet()
                        this.refreshToken = refreshToken
                    })
            }
            val token = newTokens.data
            if (token == null) {
                throw Exception("BaseResponse data is null");
            }
            // 保存新 token
            AppModel.tokenAccessSave(token.accessToken)

            // 构造新请求（带新 accessToken）
            response.request
                .newBuilder()
                .header("Authorization", "Bearer ${token.accessToken}")
                .build();
        } catch (e: Exception) {
            Logger.e("TokenAuthenticator ", e)
            // 刷新失败，清除 token 并跳转登录
            AppModel.tokenClean()
            redirectToLogin()
            null
        }
    }

    private fun redirectToLogin() {
        AppStackManager.currentActivity()?.also { activity ->
            AppStackManager.finishAllActivity()
            activity.startActivity(Intent(activity, LoginActivity::class.java));
        }
    }
}